package com.zust.zst.common.exceptions;

import com.zust.zst.common.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.zust.zst.common.enums.ResponseStatus.*;


/**
 * 全局异常处理器
 *
 * @author Gavin Zhang
 * @date 2022/11/29 20:16
 */
@RestControllerAdvice(basePackages = "com.zust.zst.controller")
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理 MethodArgumentNotValidException 异常
     * SpringMVC 参数不正确
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultVO<Map<String, String>> missingServletRequestParameterExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException ex) {

        //处理后返回错误结果
        BindingResult bindingResult = ex.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        log.warn("[MethodArgumentNotValidException], 参数校验错误信息: {}", errorMap, ex);

        // 包装 ResultVO 结果
        return ResultVO.error(METHOD_ARGUMENTS_NOT_VALID.getCode(),
                METHOD_ARGUMENTS_NOT_VALID.getDescription(),
                errorMap);
    }
}